import React, { useState, useEffect, useRef } from 'react';
import {
    Box,
    Container,
    Typography,
    Grid,
    Card,
    CardContent,
    CardMedia,
    CardActions,
    Button,
    IconButton,
    TextField,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    CircularProgress,
    Chip,
    Divider,
    Paper,
    InputAdornment,
    Snackbar,
    Alert,
    Tooltip
} from '@mui/material';
import {
    Search as SearchIcon,
    Add as AddIcon,
    Download as DownloadIcon,
    Visibility as VisibilityIcon,
    Delete as DeleteIcon,
    CloudUpload as CloudUploadIcon,
    FilterList as FilterListIcon,
    Edit as EditIcon
} from '@mui/icons-material';
import fileService from '../services/fileService';
import modelService from '../services/modelService';
import NavigationService from './NavigationService';
import { useNavigate } from 'react-router-dom';

// 模型库组件
const ModelLibrary = () => {
    // 状态管理
    const [models, setModels] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(false);
    const [selectedFile, setSelectedFile] = useState(null);
    const [modelName, setModelName] = useState('');
    const [modelDescription, setModelDescription] = useState('');
    const [notification, setNotification] = useState({ open: false, message: '', severity: 'info' });

    // 添加导航
    const navigate = useNavigate();

    // 文件上传引用
    const fileInputRef = useRef(null);

    // 初始化加载模型
    useEffect(() => {
        fetchModels();
    }, []);

    // 获取所有模型
    const fetchModels = async () => {
        try {
            setLoading(true);
            const response = await modelService.getModels();
            const modelData = response.data || [];
            console.log('获取的模型:', modelData);
            setModels(modelData);
        } catch (error) {
            console.error('获取模型失败:', error);
            showNotification('获取模型列表失败', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 处理模型上传
    const handleFileUpload = (event) => {
        const file = event.target.files[0];
        if (!file) return;

        // 自动设置模型名称（基于文件名）
        const baseName = file.name.split('.')[0];
        setModelName(baseName);
        setSelectedFile(file);

        // 打开上传对话框
        setUploadDialogOpen(true);

        // 重置文件输入，允许重新选择相同文件
        event.target.value = '';
    };

    // 上传模型到服务器
    const uploadModel = async () => {
        if (!selectedFile || !modelName) {
            showNotification('请提供所有必需信息', 'warning');
            return;
        }

        try {
            setUploadProgress(true);

            // 准备模型数据
            const modelData = {
                name: modelName,
                description: modelDescription || `导入的${selectedFile.name.split('.').pop().toUpperCase()}模型`,
                format: selectedFile.name.split('.').pop().toLowerCase(),
                color: '#3366FF',
                position: { x: 0, y: 0, z: 0 },
                rotation: { x: 0, y: 0, z: 0 },
                scale: { x: 1, y: 1, z: 1 }
            };

            // 上传模型
            const response = await fileService.importExternalModel(selectedFile, modelData);
            console.log('上传结果:', response);

            if (response && response.data) {
                showNotification('模型上传成功', 'success');
                setUploadDialogOpen(false);

                // 重置表单
                setSelectedFile(null);
                setModelName('');
                setModelDescription('');

                // 刷新模型列表
                fetchModels();
            } else {
                throw new Error('上传响应无效');
            }
        } catch (error) {
            console.error('上传模型失败:', error);
            showNotification('上传模型失败: ' + (error.message || '未知错误'), 'error');
        } finally {
            setUploadProgress(false);
        }
    };

    // 下载模型
    const downloadModel = async (modelId, format) => {
        try {
            setLoading(true);
            await fileService.downloadModelFile(modelId, format);
            showNotification('模型下载成功', 'success');
        } catch (error) {
            console.error('下载模型失败:', error);
            showNotification('下载模型失败', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 删除模型
    const deleteModel = async (modelId) => {
        if (!window.confirm('确定要删除这个模型吗？此操作不可撤销。')) {
            return;
        }

        try {
            setLoading(true);
            await modelService.deleteModel(modelId);
            showNotification('模型删除成功', 'success');
            // 更新模型列表
            setModels(models.filter(model => model.id !== modelId));
        } catch (error) {
            console.error('删除模型失败:', error);
            showNotification('删除模型失败', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 显示通知
    const showNotification = (message, severity = 'info') => {
        setNotification({
            open: true,
            message,
            severity
        });
    };

    // 处理通知关闭
    const handleNotificationClose = () => {
        setNotification({ ...notification, open: false });
    };

    // 过滤模型
    const filteredModels = models.filter(model =>
        model.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (model.description && model.description.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    // 导入到编辑器
    const importToEditor = (model) => {
        try {
            // 将模型信息存储在sessionStorage中，供编辑器读取
            sessionStorage.setItem('importedModel', JSON.stringify(model));

            // 显示通知
            showNotification('模型已准备好导入到编辑器', 'success');

            // 导航到编辑器页面
            setTimeout(() => {
                navigate('/models/geometry/create');
            }, 1000);
        } catch (error) {
            console.error('准备导入模型时出错:', error);
            showNotification('准备导入模型失败', 'error');
        }
    };

    return (
        <Container maxWidth="lg" sx={{ mt: 4, mb: 8 }}>
            <Paper elevation={3} sx={{ p: 3, borderRadius: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                    <Typography variant="h4" component="h1" gutterBottom>
                        3D模型库
                    </Typography>

                    <Box>
                        <Button
                            variant="contained"
                            color="primary"
                            startIcon={<CloudUploadIcon />}
                            onClick={() => fileInputRef.current.click()}
                            sx={{ mr: 1 }}
                        >
                            上传模型
                        </Button>
                        <input
                            type="file"
                            ref={fileInputRef}
                            onChange={handleFileUpload}
                            style={{ display: 'none' }}
                            accept=".obj,.stl,.glb,.gltf"
                        />
                    </Box>
                </Box>

                <Box sx={{ mb: 3 }}>
                    <TextField
                        fullWidth
                        placeholder="搜索模型..."
                        variant="outlined"
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        InputProps={{
                            startAdornment: (
                                <InputAdornment position="start">
                                    <SearchIcon />
                                </InputAdornment>
                            ),
                        }}
                        size="small"
                    />
                </Box>

                <Divider sx={{ mb: 3 }} />

                {loading ? (
                    <Box sx={{ display: 'flex', justifyContent: 'center', py: 5 }}>
                        <CircularProgress />
                    </Box>
                ) : (
                    <>
                        <Typography variant="subtitle1" sx={{ mb: 2 }}>
                            {filteredModels.length > 0
                                ? `共找到 ${filteredModels.length} 个模型`
                                : '暂无模型'}
                        </Typography>

                        <Grid container spacing={3}>
                            {filteredModels.map((model) => (
                                <Grid item xs={12} sm={6} md={4} key={model.id}>
                                    <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                                        <CardMedia
                                            component="div"
                                            sx={{
                                                height: 180,
                                                bgcolor: '#f0f0f0',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center'
                                            }}
                                        >
                                            {model.thumbnail ? (
                                                <img
                                                    src={model.thumbnail}
                                                    alt={model.name}
                                                    style={{ maxHeight: '100%', maxWidth: '100%', objectFit: 'contain' }}
                                                />
                                            ) : (
                                                <Box sx={{ textAlign: 'center' }}>
                                                    <Typography variant="body2" color="text.secondary">
                                                        {model.geometry?.type === 'external_model' ? (
                                                            `${model.geometry.format?.toUpperCase() || 'External'} 模型`
                                                        ) : (
                                                            `${model.geometry?.type || 'Basic'} 模型`
                                                        )}
                                                    </Typography>
                                                </Box>
                                            )}
                                        </CardMedia>

                                        <CardContent sx={{ flexGrow: 1 }}>
                                            <Typography variant="h6" gutterBottom noWrap>
                                                {model.name}
                                            </Typography>

                                            <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                                                {model.description || '无描述'}
                                            </Typography>

                                            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mt: 1 }}>
                                                <Chip
                                                    label={model.geometry?.type || 'unknown'}
                                                    size="small"
                                                    color="primary"
                                                    variant="outlined"
                                                />
                                                {model.geometry?.format && (
                                                    <Chip
                                                        label={model.geometry.format.toUpperCase()}
                                                        size="small"
                                                        color="secondary"
                                                        variant="outlined"
                                                    />
                                                )}
                                            </Box>
                                        </CardContent>

                                        <CardActions sx={{ justifyContent: 'space-between', px: 2, pb: 2 }}>
                                            <Box>
                                                <Tooltip title="查看模型">
                                                    <IconButton
                                                        color="primary"
                                                        onClick={() => NavigationService.goToEditModel(model.id)}
                                                    >
                                                        <VisibilityIcon />
                                                    </IconButton>
                                                </Tooltip>

                                                <Tooltip title="下载模型">
                                                    <IconButton
                                                        color="primary"
                                                        onClick={() => downloadModel(model.id, model.geometry?.format || 'glb')}
                                                    >
                                                        <DownloadIcon />
                                                    </IconButton>
                                                </Tooltip>
                                            </Box>

                                            <Tooltip title="删除模型">
                                                <IconButton
                                                    color="error"
                                                    onClick={() => deleteModel(model.id)}
                                                >
                                                    <DeleteIcon />
                                                </IconButton>
                                            </Tooltip>
                                        </CardActions>
                                    </Card>
                                </Grid>
                            ))}
                        </Grid>

                        {filteredModels.length === 0 && !loading && (
                            <Box sx={{ textAlign: 'center', py: 5 }}>
                                <Typography variant="body1" color="text.secondary">
                                    未找到匹配的模型
                                </Typography>
                                <Button
                                    variant="outlined"
                                    startIcon={<AddIcon />}
                                    onClick={() => fileInputRef.current.click()}
                                    sx={{ mt: 2 }}
                                >
                                    上传新模型
                                </Button>
                            </Box>
                        )}
                    </>
                )}
            </Paper>

            {/* 上传对话框 */}
            <Dialog
                open={uploadDialogOpen}
                onClose={() => !uploadProgress && setUploadDialogOpen(false)}
                maxWidth="sm"
                fullWidth
            >
                <DialogTitle>上传3D模型</DialogTitle>
                <DialogContent>
                    <Box sx={{ mb: 2 }}>
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                            已选择文件: {selectedFile?.name || '未选择文件'}
                        </Typography>
                        {selectedFile && (
                            <Chip
                                label={selectedFile.name.split('.').pop().toUpperCase()}
                                color="primary"
                                size="small"
                                sx={{ mr: 1 }}
                            />
                        )}
                    </Box>

                    <TextField
                        autoFocus
                        margin="dense"
                        label="模型名称"
                        fullWidth
                        variant="outlined"
                        value={modelName}
                        onChange={(e) => setModelName(e.target.value)}
                        required
                        disabled={uploadProgress}
                        sx={{ mb: 2 }}
                    />

                    <TextField
                        margin="dense"
                        label="模型描述"
                        fullWidth
                        variant="outlined"
                        value={modelDescription}
                        onChange={(e) => setModelDescription(e.target.value)}
                        multiline
                        rows={3}
                        disabled={uploadProgress}
                    />
                </DialogContent>

                <DialogActions sx={{ px: 3, pb: 3 }}>
                    <Button
                        onClick={() => setUploadDialogOpen(false)}
                        disabled={uploadProgress}
                    >
                        取消
                    </Button>
                    <Button
                        variant="contained"
                        onClick={uploadModel}
                        disabled={uploadProgress || !selectedFile || !modelName}
                        startIcon={uploadProgress ? <CircularProgress size={20} /> : <CloudUploadIcon />}
                    >
                        {uploadProgress ? '上传中...' : '上传'}
                    </Button>
                </DialogActions>
            </Dialog>

            {/* 通知消息 */}
            <Snackbar
                open={notification.open}
                autoHideDuration={5000}
                onClose={handleNotificationClose}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            >
                <Alert
                    onClose={handleNotificationClose}
                    severity={notification.severity}
                    variant="filled"
                >
                    {notification.message}
                </Alert>
            </Snackbar>
        </Container>
    );
};

export default ModelLibrary; 